package com.example.controller;

import com.example.dto.User;
import com.example.service.DistributedDelayQueueService;
import com.example.service.DistributedQueueService;
import com.example.service.SimpleDistributedQueueService;
import com.example.service.ZookeeperService;
import org.apache.curator.framework.api.transaction.CuratorTransaction;
import org.apache.zookeeper.CreateMode;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.util.UUID;

@RestController
public class TestController {

    Logger logger = LoggerFactory.getLogger(getClass());

    @Resource
    private DistributedQueueService distributedQueueService;

    @Resource
    private SimpleDistributedQueueService simpleDistributedQueueService;

    @Resource
    private DistributedDelayQueueService distributedDelayQueueService;

    @Resource
    private ZookeeperService zookeeperService;

    /***
     * 设置节点数据信息
     * @return
     * @throws Exception
     */
    @RequestMapping("set")
    public String set() throws Exception {
        zookeeperService.createNode(CreateMode.EPHEMERAL_SEQUENTIAL, "/yyyy/" + "s");
        return "yyyy";
    }

    /***
     * 发送消息,自定义分布式队列
     * @return
     * @throws Exception
     */
    @RequestMapping("send")
    public String send() throws Exception {
        String uuid = UUID.randomUUID().toString();
        distributedQueueService.getDistributedQueue().put(new User(uuid));
        return uuid;
    }

    /***
     * 简单队列信息，主要是字符串
     * @return
     * @throws Exception
     */
    @RequestMapping("sendSimple")
    public String sendSimple() throws Exception {
        String uuid = UUID.randomUUID().toString();
        simpleDistributedQueueService.getSimpleDistributedQueue().offer(uuid.getBytes());
        return uuid;
    }

    /****
     * 分布式延迟队列，额延迟操作
     * @return
     * @throws Exception
     */
    @RequestMapping("sendDelay")
    public String sendDelay() throws Exception {
        long time = System.currentTimeMillis() + 1 * 60 * 1000;
        String uuid = UUID.randomUUID().toString();
        logger.warn("sendDelay： " + uuid);
        distributedDelayQueueService.getDistributedDelayQueue().put(new User(uuid), time);
        return uuid;
    }

    /****
     * 基于zk的事务操作
     * @throws Exception
     */
    @RequestMapping(value = "setNodeAndDataInTx")
    public void setNodeAndDataInTx() throws Exception {
        CuratorTransaction curatorTransaction = zookeeperService.getCuratorTransaction(getClass().getName());
        curatorTransaction.setData().forPath("/zk/data", "xxxx".getBytes()).and().delete().forPath("/zk/d1").and().commit();
    }
}